package com.akk.business;

import com.akk.common.enums.UserEnums;
import com.akk.module.app.service.AppService;
import com.akk.module.user.entity.User;
import com.akk.module.user.entity.UserWallet;
import com.akk.module.user.model.request.ForgetLoginPwdRequest;
import com.akk.module.user.model.request.UpdateLoginPwdRequest;
import com.akk.module.user.model.request.UserLoginRequest;
import com.akk.module.user.model.request.UserRegisterRequest;
import com.akk.module.user.model.response.UserLoginResponse;
import com.akk.module.user.service.UserService;
import com.akk.exception.RestBusinessException;
import com.akk.module.user.service.UserWalletService;
import com.akk.utils.Constants;
import com.akk.utils.IDUtils;
import com.akk.utils.ValidateUtil;
import com.akk.utils.VerificationCodeUtil;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class LoginBusiness {

    @Autowired
    UserService userService;

    @Autowired
    AppService appService;

    @Autowired
    UserWalletService userWalletService;


    public UserLoginResponse userLogin(UserLoginRequest request) {
        User user = userService.findByPhoneAndAppId(request.getPhone(), request.getAppId());
        if (user == null)
            throw new RestBusinessException("用户不存在.");
        if (!user.getLoginPwd().equals(new Sha256Hash(request.getLoginPwd()).toHex()))
            throw new RestBusinessException("密码不正确.");
        if(user.getStatus() == UserEnums.UserStatus.LOCK.getValue())
            throw new RestBusinessException("用户被锁定.");
        UserLoginResponse response = new UserLoginResponse();
        response.setSpreadUsername(userService.findByUserId(user.getSpreadId()).getUsername());
        response.setPhone(user.getPhone());
        response.setAgentId(user.getAgentId());
        response.setUserGradeId(user.getUserGradeId());
        response.setAppId(user.getAppId());
        response.setCreateDate(user.getCreateDate());
        response.setFacePath(user.getFacePath());
        response.setUsername(user.getUsername());
        response.setSpreadId(user.getSpreadId());
        response.setIdCard(user.getIdCard());
        response.setRealAuth(user.getRealAuth());
        response.setUserId(user.getUserId());
        return response;
    }
    @Transactional
    public boolean userRegister(UserRegisterRequest request, HttpServletRequest servletRequest) {
        String phone = request.getPhone();
        String loginPwd = new Sha256Hash(request.getLoginPwd()).toHex();
        String appId = request.getAppId();
        String username = request.getUsername();
        String idCard = request.getIdCard();
        String spreadPhone = request.getSpreadPhone();
        String transPwd = new Sha256Hash(request.getTransPwd()).toBase64().toUpperCase();
        String checkValue = (String) servletRequest.getSession().getAttribute(phone);
        if (!"success".equals(checkValue))
            throw new RestBusinessException("手机尚未通过验证或验证失效.");
        User userEntity = userService.findByPhoneAndAppId(phone,appId);
        if (userEntity != null) {
            throw new RestBusinessException("手机号已经被注册.");
        }
        User spreadUser = userService.findByPhoneAndAppId(spreadPhone,appId);
        User user = new User();
        String userId = IDUtils.getPK();
        user.setUserId(userId);
        user.setPhone(phone);
        user.setAppId(appId);
        user.setLoginPwd(loginPwd);
        user.setUsername(username);
        user.setIdCard(idCard);
        user.setRealAuth(UserEnums.RealAuth.NO.getValue());
        user.setTransPwd(transPwd);
        user.setStatus(UserEnums.UserStatus.NORMAL.getValue());
        user.setSpreadId(spreadUser.getUserId());
        user.setCreateDate(new Date());
        user.setUserGradeId(appService.findByAppId(request.getAppId()).getGradeInitId());
        user.setRealType(UserEnums.RealType.NONE.getValue());
        user.setAgentId(spreadUser.getAgentId());
        userService.insert(user);
        servletRequest.getSession().removeAttribute(phone);
        UserWallet wallet = new UserWallet();
        wallet.setBalance(0.0);
        wallet.setPoints(0);
        wallet.setRebate(0.0);
        wallet.setTotalRebate(0.0);
        wallet.setCreateDate(new Date());
        wallet.setUpdateDate(new Date());
        wallet.setUserId(userId);
        wallet.setStatus(0);
        userWalletService.insert(wallet);
        return true;
    }

    public boolean smsCode(String phone, HttpServletRequest request) {
        if (!ValidateUtil.isMobileNO(phone))
            throw new RestBusinessException("手机号格式错误.");
        if(request.getSession().getAttribute(Constants.SMS_CODE_TIMEOUT)!=null){
            Long timeStamp = Long.valueOf(request.getSession().getAttribute(Constants.SMS_CODE_TIMEOUT).toString());
            if(timeStamp+(60*1000) > new Date().getTime()){
                throw new RestBusinessException("每次发送短信需间隔60S.");
            }
        }
        try {
            String code = VerificationCodeUtil.getCode();
            //String content = MsgTemplate.getTimingToUserRegText(code);
            //content = java.net.URLEncoder.encode(content,"utf-8");
            //MessageFactory.build(MsgType.SPECIAL.getValue()).sendSpecialMessage(phone,content,"","","","");
            // 验证有效期10分钟
            System.out.println("code:"+code);
            request.getSession().setMaxInactiveInterval(60 * 30);
            request.getSession().setAttribute(phone,code);
            request.getSession().setAttribute(Constants.SMS_CODE_TIMEOUT,new Date().getTime());
            return true;
        } catch (Exception e) {
            throw new RestBusinessException("系统异常，请稍后重试.");
        }
    }

    public boolean updateLoginPwd(UpdateLoginPwdRequest request) {
        String loginPwd = new Sha256Hash(request.getLoginPwd()).toHex();
        String newLoginPwd = new Sha256Hash(request.getNewLoginPwd()).toHex();
        User user = userService.findByPhoneAndAppId(request.getPhone(),request.getAppId());
        if(user == null || !user.getLoginPwd().equals(loginPwd))
            throw new RestBusinessException("用户不存在或密码错误.");
        user.setLoginPwd(newLoginPwd);
        userService.update(user);
        return true;

    }

    public boolean forgetPwd(ForgetLoginPwdRequest request, HttpServletRequest servletRequest) {
        if(!request.getCode().equals(servletRequest.getSession().getAttribute(request.getPhone())))
            throw new RestBusinessException("验证码错误.");
        servletRequest.getSession().removeAttribute(request.getPhone());
        User user = userService.findByPhoneAndAppId(request.getPhone(),request.getAppId());
        if(user == null)
            throw new RestBusinessException("用户信息未找到.");
        user.setLoginPwd(new Sha256Hash(request.getNewLoginPwd()).toHex());
        userService.update(user);
        return true;
    }
}
